AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')

function ENT:Use(activator,caller)
	if (self.LastUsed+0.5>CurTime()) then
		self.LastUsed = CurTime()
	else
		self.LastUsed = CurTime()
		if (activator==self.dt.Owner || !self.Locked) then
			if (activator==self.dt.Owner) then
				self.Locked = true
			end
			umsg.Start("moneyvaultgui", activator)
				umsg.String(self.Amount)
				umsg.Short(self.Entity:EntIndex())
			umsg.End()
		else
			Notify(activator,4,3,"This money vault is locked! Use a lock pick to force it open.")
		end
	end
end

function ENT:OnRemove()
	self.Entity:DropMoney()	
end

function ENT:StartTouch(money)
	if (money:GetClass()=="item_money") then
		if(money.Time == nil) then
			money.Time = CurTime() - 10
		end
		if (money.Time < CurTime() - 10) then
			self.Amount = self.Amount + money.Value
			money.Value = 0
			money:Remove()	
		end
	end
end

function ENT:DropMoney(ply)
	if(self.Amount ~= 0) then
	local moneybag = ents.Create("item_money")
		moneybag:SetPos(self:GetPos() + Vector(0,0,17))
		moneybag:SetAngles(self.Entity:GetAngles())
		moneybag:Spawn()
		moneybag.Value = self.Amount
		moneybag.Time = CurTime()
		self.Amount = 0
	end
end

function ENT:SetUnlocked()
	self.Locked = false
end

function ccWithdrawMoney(ply, cmd, args)
	if (args[1]==nil) then return end
	if (!ents.GetByIndex(args[1]):IsValid()) then return end
	local vault = ents.GetByIndex(args[1])
	if (vault:GetClass()!="struct_moneyvault" || ply:GetPos():Distance(vault:GetPos())>200) then return end
	if (vault.Locked && ply!=vault.dt.Owner) then return end
	vault:DropMoney(ply)
end
concommand.Add("withdrawmoney", ccWithdrawMoney)